package com.zja.www.view;

import com.zja.www.controller.BaseController;
import com.zja.www.entity.Department;
import com.zja.www.service.DepartmentService;
import com.zja.www.service.DoctorService;
import com.zja.www.service.MedicalRecordService;
import com.zja.www.service.UserService;


import java.util.Collections;
import java.util.List;


public class DepartmentView extends BaseController {
    private final DepartmentService departmentService;
    private final DoctorService doctorService;
    private final MedicalRecordService medicalRecordService;
    private  UserView userView;


    public DepartmentView(
            UserService userService,
            DoctorService doctorService,
            MedicalRecordService medicalRecordService,
            DepartmentService departmentService

    ) {
        super(userService, doctorService, medicalRecordService);
        this.departmentService = departmentService;
        this.doctorService = doctorService;
        this.medicalRecordService = medicalRecordService;
    }

    public void setUserView(UserView userView) {
        this.userView = userView;
    }

    /**
     * 显示科室选择界面
     * @return 选择的科室ID，0表示返回，-1表示错误
     */
    public int showDepartmentSelection() {
        List<Department> departments = getAvailableDepartments();
        if (departments.isEmpty()) {
            System.out.println("当前没有可用科室");
            return -1;
        }

        printDepartmentList(departments);
        return processUserSelection(departments);
    }


    private List<Department> getAvailableDepartments() {
        try {
            List<Department> departments = departmentService.getAllDepartments();
            return departments != null ? departments : Collections.emptyList();
        } catch (Exception e) {
            System.err.println("获取科室列表失败: " + e.getMessage());
            return Collections.emptyList();
        }
    }

    private void printDepartmentList(List<Department> departments) {
        System.out.println("\n==== 科室列表 ====");
        for (int i = 0; i < departments.size(); i++) {
            Department dept = departments.get(i);
            System.out.printf("%2d. %-10s %s\n",
                    i + 1,
                    dept.getName(),
                    dept.getDescription());
        }
        System.out.println(" 0. 返回上级");
    }

    private int processUserSelection(List<Department> departments) {
        while (true) {
            System.out.print("请选择科室编号: ");
            int choice = readIntInput();

            if (choice == 0) {
                userView.showHospitalSystem();
                return 0;
            } else if (choice > 0 && choice <= departments.size()) {
                return departments.get(choice - 1).getId();
            }
            System.out.println("无效选择，请输入0~" + departments.size());
        }
    }
}
